package src.week8.实验;

import src.week6.BinaryTreeNode;
import src.week8.实验.LinkedBinaryTree;
import java.util.ArrayList;

public class InfixToSuffix extends LinkedBinaryTree implements Comparable {
    public BinaryTreeNode node;
    public InfixToSuffix(){
    }
    public BinaryTreeNode BuildTree(String Line){
        ArrayList<String > symbo = new ArrayList<>();
        ArrayList<LinkedBinaryTree> num = new ArrayList<>();
        String x[] = Line.split(" ");

        for (int i =0;i<x.length;i++){
            if (x[i].equals("(")){
                String temp1 = "";
                while (true) {
                    if (!x[i+1].equals(")")){
                        temp1 += x[i+1] + " ";
                    }
                    else {
                        break;
                    }
                    i++;
                }
                LinkedBinaryTree temp = new LinkedBinaryTree();
                temp.root = BuildTree(temp1);
                num.add(temp);
                i++;
            }
            if (x[i].equals("+")||x[i].equals("-")){
                symbo.add(String.valueOf(x[i]));
            }
            else if (x[i].equals("*")||x[i].equals("/")){
                LinkedBinaryTree left=num.remove(num.size()-1);
                String temp2=String.valueOf(x[i]);
                if (!x[i+1].equals("(")){
                    LinkedBinaryTree right = new LinkedBinaryTree(String.valueOf(x[i+1]));
                    LinkedBinaryTree node = new LinkedBinaryTree(temp2, left, right);
                    num.add(node);
                }
                else {
                    String temp3 = "";
                    while (true) {
                        if (!x[i+1].equals(")")){
                            temp3+=String.valueOf(x[i+1]);
                        }
                        else {
                            break;
                        }
                        i++;
                    }
                    LinkedBinaryTree temp4 = new LinkedBinaryTree();
                    temp4.root = BuildTree(temp3);
                    LinkedBinaryTree node1 = new LinkedBinaryTree(temp2, left, temp4);
                    num.add(node1);
                }
            }else {
                num.add(new LinkedBinaryTree(x[i]));}
        }
        while (symbo.size() > 0) {
            LinkedBinaryTree leftnode = num.remove(0);
            LinkedBinaryTree rightnode = num.remove(0);
            String oper = symbo.remove(0);
            LinkedBinaryTree node2 = new LinkedBinaryTree(oper, left, right);
            num.add(0, node2);
        }
        node = (num.get(0)).root;
        return node;
    }
    @Override
    public int compareTo(Object o) {
        if (o=="*"||o=="/"){
            return 1;
        }
        else {
            return -1;
        }

    }
}






